package org.micode.common.weixin;

import org.apache.commons.lang3.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 微信相关的工具类
 */
public class WxUtils {

    final static String SERVICE_WECHAT_URL = "https://servicewechat.com/";

    public static String getAppIdFromReferer(String referer) {
        if (!StringUtils.isEmpty(referer)) {
            int pos = referer.indexOf(SERVICE_WECHAT_URL);
            if (pos >= 0) {
                String sub = referer.substring(pos + SERVICE_WECHAT_URL.length());
                int endPos = sub.indexOf('/');
                return sub.substring(0, endPos);
            }
        }
        return null;
    }

    public static boolean verifyRequestReferer(String appId, String referer) {
        String regEx = "^" + SERVICE_WECHAT_URL + appId + "/(\\d+(\\.\\d+)?|devtools)/page-frame.html$";
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(referer);
        return matcher.matches();
    }

    public static void main(String[] args) {
        System.out.println(getAppIdFromReferer("https://servicewechat.com/fdklsjareoii430/drew"));
    }

}
